package com.qing.annotation.factory.module;

import com.qing.annotation.factory.SimpleFactory;
import org.apache.commons.lang3.StringUtils;

import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;

/**
 * 工厂注解类实例
 *
 * @author qing
 * 23/9/17
 */
public class SimpleFactoryAnnotatedClass {

    /**
     * 类元素
     */
    private final TypeElement mTypeElement;

    /**
     * 工厂id
     */
    private final String mFactoryId;

    /**
     * 全类名
     */
    private String mQualifiedSuperClassName;

    /**
     * ClassSimpleName
     */
    private String mSimpleTypeName;

    public SimpleFactoryAnnotatedClass(TypeElement classElement) throws IllegalArgumentException {
        this.mTypeElement = classElement;
        SimpleFactory annotation = classElement.getAnnotation(SimpleFactory.class);
        mFactoryId = annotation.id();

        if (StringUtils.isEmpty(mFactoryId)) {
            throw new IllegalArgumentException(String.format("id() in @%s for class %s is null or empty! that's not allowed", SimpleFactory.class.getSimpleName(), classElement.getQualifiedName().toString()));
        }

        // Get the full QualifiedTypeName
        try {
            Class<?> clazz = annotation.type();
            mQualifiedSuperClassName = clazz.getCanonicalName();
            mSimpleTypeName = clazz.getSimpleName();
        } catch (MirroredTypeException mte) {
            DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();
            TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();
            mQualifiedSuperClassName = classTypeElement.getQualifiedName().toString();
            mSimpleTypeName = classTypeElement.getSimpleName().toString();
        }
    }

    /**
     * 获取在{@link SimpleFactory#id()}中指定的id
     * return the id
     */
    public String getId() {
        return mFactoryId;
    }

    /**
     * 获取在{@link SimpleFactory#type()}指定的类型合法全名
     *
     * @return qualified name
     */
    public String getQualifiedFactoryGroupName() {
        return mQualifiedSuperClassName;
    }


    /**
     * 获取在 {@link SimpleFactory#type()} 中指定的类型的简单名字
     *
     * @return qualified name
     */
    public String getSimpleFactoryGroupName() {
        return mSimpleTypeName;
    }

    /**
     * 获取被@Factory注解的原始元素
     */
    public TypeElement getTypeElement() {
        return mTypeElement;
    }

    @Override
    public String toString() {
        return "FactoryAnnotatedClass{" + "mTypeElement=" + mTypeElement + ", mQualifiedSuperClassName='" + mQualifiedSuperClassName + '\'' + ", mSimpleTypeName='" + mSimpleTypeName + '\'' + ", mFactoryId='" + mFactoryId + '\'' + '}';
    }
}